import { Square } from "./Square"
import { IPoint, IShape } from "./types"
/**
 * 只做一件事，一个数组（相对位置）+一个中心点+集体颜色
 */
export class SquareGroup {
    private _squares: readonly Square[]

    constructor(private _shape: IShape, private _centerPoint: IPoint, private _color: string) {
        // 设置小方块数组
        const arr: Square[] = []
        this._shape.forEach((point) => {
            const sq = new Square({ x: this._centerPoint.x + point.x, y: this._centerPoint.y + point.y }, this._color)
            arr.push(sq)
        })
        this._squares = arr
    }

    get shape() {
        return this._shape
    }

    set shape(val) {
        this._shape = val
    }

    get squares() {
        return this._squares
    }

    get centerPoint() {
        return this._centerPoint
    }

    set centerPoint(val: IPoint) {
        this._centerPoint = val
        this.setSquarePoint()
    }

    // 旋转方向是否为顺时针，默认顺时针
    protected isClock: boolean = true
    /**
     * 根据当前IShape，计算目标形状
     */
    afterRotateShape(): IShape {
        // 顺时针旋转
        if (this.isClock) {
            return this._shape.map((p) => {
                const newP: IPoint = {
                    x: -p.y,
                    y: p.x
                }
                return newP
            })
        } else {
            return this._shape.map((p) => {
                const newP: IPoint = {
                    x: p.y,
                    y: -p.x
                }
                return newP
            })
        }
    }

    /**
     * 根据中心点坐标，以及形状设置小方块坐标[内部方法]
     * 只要形状改变就调用该小方块坐标就变化
     */
    private setSquarePoint() {
        this._shape.forEach((p, i) => {
            this._squares[i].point = {
                x: this._centerPoint.x + p.x,
                y: this._centerPoint.y + p.y
            }
        })
    }

    /**
     * 旋转，需要计算旋转
     */
    rotate() {
        const newShape = this.afterRotateShape()
        this._shape = newShape
        // 注意小方块对象坐标变化
        this.setSquarePoint()
    }
}
